import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {LoginUserService} from "../../../services/login-user.service";
import {Router} from "@angular/router";
import {LoginHttpService} from "../service/login-http.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {concat} from "rxjs";
import {AppRoutingCache} from "../../../rootStrategy/app-routing-cache";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {

  userForm = new FormGroup({
    account: new FormControl('', Validators.required),
    password: new FormControl('', Validators.required)
  })
  loading = false

  constructor(private loginUserService: LoginUserService, private router: Router, private loginHttpService: LoginHttpService,
              private message: NzMessageService) {
  }

  ngOnInit(): void {
    AppRoutingCache.cleanRouteSnapshot()
  }

  doLogin() {
    this.loading = true
    let valid = true
    for (const i in this.userForm.controls) {
      this.userForm.controls[i].markAsDirty();
      this.userForm.controls[i].updateValueAndValidity();
      if (!this.userForm.controls[i].valid) {
        valid = false
      }
    }
    if (!valid) {
      this.loading = false
      return
    }
    this.loginUserService.clean()
    const out = this.loginUserService.logout()
    const login = this.loginHttpService.login(this.userForm.get('account').value, this.userForm.get('password').value)
    concat(out, login)

    login.subscribe(value => {
      if (value && value.account) {
        this.loginUserService.currentUser = value
        this.loginUserService.refreshToken = value.refreshToken
        this.router.navigate(["/welcome"]).then(() => this.message.success('登陆成功'))
      } else {
        this.message.error("账号或密码不正确!")
      }
    }, (e) => {
      this.loading = false
      const response = e.error;
      if (response) {
        if (response.status === 'PASSWORD_ERROR') {
          this.message.error("账号或密码不正确")
        } else {
          this.message.error(`${response.status}:${response.message}`);
        }
      } else {
        this.message.error(`${e.status}:${e.message}`)
      }
    }, () => this.loading = false)
  }

}
